﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using LicenseData;

namespace GenCallDB
{
	class Program
	{
		public const int LicenseStatusIndex = 5;
		public const int LicenseIdIndex = 1;

		public const string LicenseStatusActive = "A";

		static void Main( string[] args )
		{
			string
				input;
			string[]
				values;
			int
				count;
			ActiveLicenses
				activeLicenses = new ActiveLicenses();
			LicenseDictionary
				licenseDictionary;
			LicenseDetails
				details;

			Console.WriteLine( "Reading current license file..." );
			licenseDictionary = LicenseDictionary.GetLicenseDictionary();
			Console.WriteLine( "Read {0} total current licenses", licenseDictionary.Count );

			Console.WriteLine( "Opening HD..." );
			try
			{
				using ( StreamReader reader = File.OpenText( "HD.dat" ) )
				{
					count = 0;
					while ( ( input = reader.ReadLine() ) != null )
					{
						if ( !string.IsNullOrWhiteSpace( input ) )
						{
							++count;
							values = input.Split( '|' );
							if ( values[ LicenseStatusIndex ] == LicenseStatusActive )
							{
								activeLicenses[ int.Parse( values[ LicenseIdIndex ] ) ] = true;
							}
						}
					}
				}

				Console.WriteLine( "Read {0} entries from HD", count );
			}
			catch
			{
				Console.WriteLine( "Error reading from HD" );
				return;
			}

			Console.WriteLine( "Opening EN..." );
			try
			{
				using ( StreamReader reader = File.OpenText( "EN.dat" ) )
				{
					while ( ( input = reader.ReadLine() ) != null )
					{
						if ( !string.IsNullOrWhiteSpace( input ) )
						{
							values = input.ToUpper().Replace( "'", string.Empty ).Split( '|' );
							if ( activeLicenses[ int.Parse( values[ LicenseIdIndex ] ) ] )
							{
								if ( !string.IsNullOrWhiteSpace( values[ LicenseDetails.CallsignIndex ] ) &&
									!string.IsNullOrWhiteSpace( values[ LicenseDetails.NameIndex ] ) )
								{
									details = new LicenseDetails( values );
									licenseDictionary.UpdateLicense( details );
								}
							}
						}
					}
				}
			}
			catch
			{
				Console.WriteLine( "Error reading from EN" );
				return;
			}

			Console.WriteLine( "Total unchanged licenses: {0}", licenseDictionary.TotalUnchangedLicenses );
			Console.WriteLine( "Total updated licenses: {0}", licenseDictionary.TotalUpdatedLicenses );
			Console.WriteLine( "Total removed licenses: {0}", licenseDictionary.TotalRemovedLicenses );
			Console.WriteLine( "Saving files..." );

			licenseDictionary.UpdateLicenseDataFile();

			Console.WriteLine( "Total SQL files created: {0}", licenseDictionary.TotalSqlFilesCreated );

			Console.WriteLine( "Processing complete, press Enter to exit..." );
			Console.ReadLine();
		}
	}
}
